package com.tj.collection.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.EntityUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.jsoniter.output.JsonStream;
import com.tj.collection.db.dao.ClAgentsDao;
import com.tj.collection.db.dao.ClStageDao;
import com.tj.collection.db.domain.Admin;
import com.tj.collection.db.entity.ClAgentsEntity;
import com.tj.collection.db.entity.ClStageEntity;
import com.tj.collection.db.service.AdminService;
import com.tj.collection.service.dto.ClAgentsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: pavan
 * Date: 2019/9/9
 * Time: 上午10:16
 */
@Component
public class AgentManageService {
    public static final Log LOGGER = LogFactory.getLog(AgentManageService.class);


    @Autowired
    private ClAgentsDao clAgentsDao;

    @Autowired
    private ClStageDao clStageDao;

    @Autowired
    private AdminService adminService;

    @Autowired
    private AllocationService allocationService;

    /**
     * 查询催收员列表
     *
     * @param merchantCode
     * @param page
     * @return
     */
    public List<ClAgentsVo> getAgentList(String merchantCode, String stageCode, Page page) {
        List<ClAgentsEntity> clAgentsEntityList = clAgentsDao.selectAgentListByMerchantCode(merchantCode, stageCode, page);
        if (CollectionUtils.isEmpty(clAgentsEntityList)) {
            return new ArrayList<>();
        }
        List<ClStageEntity> clStageEntities = clStageDao.getStagesByMerchantCode(merchantCode);
        Map<String, ClStageEntity> stageEntityMap = EntityUtils.makeEntityMap(clStageEntities, "stageCode");
        List<ClAgentsVo> clAgentsVoList = new ArrayList<>();
        for (ClAgentsEntity entity : clAgentsEntityList) {
            ClStageEntity clStageEntity = stageEntityMap.get(entity.getStageCode());
            ClAgentsVo clAgentsVo = new ClAgentsVo();
            clAgentsVo.setAdminId(entity.getAdminId().intValue())
                    .setStageCode(entity.getStageCode())
                    .setStageName(clStageEntity.getStageName())
                    .setMerchantCode(entity.getMerchantCode())
                    .setType(entity.getType())
                    .setMaxOrdersNum(entity.getMaxOrdersNum())
                    .setMinOrdersNum(entity.getMinOrdersNum())
                    .setStatus(entity.getStatus());
            try {
                List<String> userLanguageList = new ArrayList<>();
                JSONObject jsonObject = JSON.parseObject(entity.getExtraAttribute());
                JSONArray languageWeight = jsonObject.getJSONArray("languageWeight");
                for (int i = 0; i < languageWeight.size(); i++) {
                    userLanguageList.add(languageWeight.getJSONObject(i).getString("userLanguage"));
                }
                clAgentsVo.setUserLanguageList(CollectionUtils.isNotEmpty(userLanguageList) ? userLanguageList : new ArrayList<>());
            } catch (Exception e) {
            }
            Admin admin = null;
            try {
                admin = adminService.getOneAdminByAdmin(entity.getAdminId().longValue());
            } catch (Exception e) {
                LOGGER.info("查询管理员信息错误,adminId:{}", entity.getAdminId(), e);
            }
            if (admin == null) {
                continue;
            }
            clAgentsVo.setName(admin.getName());
            clAgentsVoList.add(clAgentsVo);
        }
        return clAgentsVoList;
    }

    /**
     * 保存信审人员信息
     *
     * @param clAgentsVo
     */
    public void saveAgent(ClAgentsVo clAgentsVo) {
        if (clAgentsVo.getAdminId() == null) {
            throw new ApplicationException("adminId不能为空");
        }
        if (StringUtils.isEmpty(clAgentsVo.getStageCode())) {
            throw new ApplicationException("催收员bucket不能为空");
        }
        Admin admin = adminService.getOneAdminByAdmin(clAgentsVo.getAdminId().longValue());
        ClAgentsEntity clAgentsEntity = clAgentsDao.getByAdminId(admin.getId().intValue());

        if (clAgentsEntity == null) {
            clAgentsEntity = new ClAgentsEntity();
            clAgentsEntity.setAdminId(clAgentsVo.getAdminId());
            clAgentsEntity.setAdminName(StringUtils.isNotEmpty(clAgentsVo.getName()) ? clAgentsVo.getName() : admin.getName());
            clAgentsEntity.setStageCode(clAgentsVo.getStageCode());
            clAgentsEntity.setMerchantCode(admin.getMerchantCode());

            JSONObject jsonObject = new JSONObject();
            JSONArray languageWeight = new JSONArray();
            for (String userLanguage : clAgentsVo.getUserLanguageList()) {
                JSONObject item = new JSONObject();
                item.put("userLanguage", userLanguage);
                item.put("weight", 1);
                languageWeight.add(item);
            }
            jsonObject.put("languageWeight", languageWeight);
            clAgentsEntity.setExtraAttribute(jsonObject.toJSONString());
            clAgentsEntity.setType(1);//TODO keng 内催、外催？
            clAgentsEntity.setMaxOrdersNum(clAgentsVo.getMaxOrdersNum());
            clAgentsEntity.setMinOrdersNum(clAgentsVo.getMinOrdersNum());
            clAgentsEntity.setStatus(1);
            clAgentsDao.insert(clAgentsEntity);
        } else {

            //如果阶段不同  则全部撤单
            boolean isReallocated = false;
            if (!clAgentsEntity.getStageCode().equals(clAgentsVo.getStageCode())) {
                //当前agent置为无效状态
                clAgentsEntity.setDeleted(true);
                clAgentsDao.updateByPrimaryKey(clAgentsEntity);

                //撤回所有分单
                allocationService.deleteAgent(clAgentsEntity.getAdminId(), null);
                isReallocated = true;

                //更改当前agent的bucket 然后置为有效
                clAgentsEntity.setStageCode(clAgentsVo.getStageCode());
                clAgentsEntity.setDeleted(false);
            }


            if (CollectionUtils.isNotEmpty(clAgentsVo.getUserLanguageList())) {
                JSONObject jsonObject = new JSONObject();
                JSONArray languageWeight = new JSONArray();
                for (String userLanguage : clAgentsVo.getUserLanguageList()) {

                    JSONObject item = new JSONObject();
                    item.put("userLanguage", userLanguage);
                    item.put("weight", 1);
                    languageWeight.add(item);
                }
                jsonObject.put("languageWeight", languageWeight);
                clAgentsEntity.setExtraAttribute(jsonObject.toJSONString());

                if (!isReallocated) {
                    allocationService.deleteAgent(clAgentsEntity.getAdminId(), clAgentsVo.getUserLanguageList());
                }
            }
            clAgentsEntity.setType(1);//TODO keng 内催、外催？
            if (clAgentsVo.getMaxOrdersNum() != null) {
                clAgentsEntity.setMaxOrdersNum(clAgentsVo.getMaxOrdersNum());
            }
            if (clAgentsVo.getMinOrdersNum() != null) {
                clAgentsEntity.setMinOrdersNum(clAgentsVo.getMinOrdersNum());
            }
            if (clAgentsVo.getStatus() != null) {
                clAgentsEntity.setStatus(clAgentsVo.getStatus());
            }
            clAgentsDao.updateByPrimaryKey(clAgentsEntity);
        }
    }

}
